package com.financial.service.integralpay.service.impl;

import com.financial.service.integralpay.config.UrlConstants;
import com.financial.service.integralpay.connector.FinancialPlatformPayFegin;
import com.financial.service.integralpay.constants.FinancialPayreceiptPlatbalanceEnumConstants;
import com.financial.service.integralpay.dao.FinancialIntegralPayReceiptDao;
import com.financial.service.integralpay.domain.FinancialIntegralPayReceiptDO;
import com.financial.service.integralpay.service.FinancialIntegralPayService;
import com.financial.service.integralpay.utils.DateUtils;
import com.financial.service.integralpay.utils.apiresult.ApiResult;
import com.financial.service.integralpay.utils.balanceutils.HttpClientUtils;
import com.financial.service.integralpay.utils.balanceutils.JsonUtils;
import com.financial.service.integralpay.utils.balanceutils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FinancialIntegralPayServiceImpl implements FinancialIntegralPayService {

    public static final Logger logger = LoggerFactory.getLogger(FinancialIntegralPayServiceImpl.class);
    @Autowired
    private FinancialPlatformPayFegin platformPayFegin;
    @Autowired
    private FinancialIntegralPayReceiptDao gyintegralPayReceiptDao;
    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private HttpClientUtils httpClientUtils;

    @Override
    public Map<String, Object> integralpay(Map<String, Object> reqMap) {
        return null;
    }

    @Override
    public Map<String, Object> integralpayAsyn(Map<String, Object> reqMap) {
        logger.info("integralpayAsyn------金融支付中心接收够样积分中心信息"+JsonUtils.objectToJson(reqMap));
        String results=  "";
        Object temp = "";
        String orderNum ="";
        try {
            temp = reqMap.get("currencyCode");
            String currencyCode = temp!= null ? temp.toString():null;
            temp = reqMap.get("prePayNo");
            String prePayNo = temp!= null ? temp.toString():null;
            temp = reqMap.get("payCurrency");
            String payCurrency = temp!= null ? temp.toString():null;
            temp = reqMap.get("customerId");
            String customerUuid = temp!= null ? temp.toString():null;
            temp = reqMap.get("orderNum");
            orderNum = temp!= null ? temp.toString():null;
            temp = reqMap.get("platformBusnum");
            String platformBusnum = temp!= null ? temp.toString():null;
            int platfromId = platformPayFegin.getPlatfromId(platformBusnum);
            //todo 积分预支付异步信息通知优点平台回执记录
            FinancialIntegralPayReceiptDO gyintegralPayReceiptDO = new FinancialIntegralPayReceiptDO();
            gyintegralPayReceiptDO.setResponseType("2");
            gyintegralPayReceiptDO.setPayno(prePayNo);
            gyintegralPayReceiptDO.setPaymoney(new BigDecimal(payCurrency));
            gyintegralPayReceiptDO.setCustomeruuid(customerUuid);
            gyintegralPayReceiptDO.setGmtCreate(new Date());
            gyintegralPayReceiptDO.setGmtModified(new Date());
            gyintegralPayReceiptDO.setIsDelete("1");
            gyintegralPayReceiptDO.setSubject("积分异步");
            gyintegralPayReceiptDO.setOpetime(DateUtils.getNowTimeStr());
            gyintegralPayReceiptDO.setOrderno(orderNum);
            gyintegralPayReceiptDO.setPlatfromappid(String.valueOf(platfromId));
            if (currencyCode.equals("0")){
                gyintegralPayReceiptDO.setState("交易成功");
            }else {
                gyintegralPayReceiptDO.setState("交易失败");
            }
            gyintegralPayReceiptDao.save(gyintegralPayReceiptDO);
            //通知优店支付中心
            Object temp1 = null;
            Map<String, String> authMap = new HashMap<>();
            logger.info("integral--------拼接请求参数对接够样平台请求地址:{},对接参数:{}",UrlConstants.INTEGRAL_ASYN_URL,JsonUtils.objectToJson(reqMap));
            results = httpClientUtils.doPost(UrlConstants.INTEGRAL_ASYN_URL,reqMap);
            logger.info("积分支付异步通知优店结果"+results);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("orderNum:{},积分支付平台回调够样优店失败:{}",orderNum,e.getMessage());
        }
        return JsonUtils.jsonToMap(results);
    }

    @Override
    public String queryIntegralpay(Map<String, Object> paraMap) {
        logger.info("接收优点积分支付查询参数"+JsonUtils.objectToJson(paraMap));
        String resultStr ="";
        String orderNum = paraMap.get("orderNum").toString();
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("orderNum",orderNum);
        try {
            logger.info("integral--------拼接请求参数对积分中心请求地址:{},对接参数:{}",UrlConstants.INTEGRAL_ASYN_URL,JsonUtils.objectToJson(reqMap));
            resultStr = httpClientUtils.doPost(UrlConstants.INTEGRAL_QUERY_URL,reqMap);
            logger.info("调用够样积分主动查询返回信息"+resultStr);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("查询积分预支付信息失败!"+e.getMessage());
        }
        return resultStr;
    }

    @Override
    public FinancialIntegralPayReceiptDO get(Integer id) {
        return null;
    }

    @Override
    public List<FinancialIntegralPayReceiptDO> list(Map<String, Object> map) {
        return null;
    }

    @Override
    public int count(Map<String, Object> map) {
        return 0;
    }

    @Override
    public int update(FinancialIntegralPayReceiptDO gyintegralPayReceipt) {
        return 0;
    }

    @Override
    public int save(FinancialIntegralPayReceiptDO gyintegralPayReceipt) {
        return 0;
    }


    @Override
    public int remove(Integer id) {
        return 0;
    }

    @Override
    public int batchRemove(Integer[] ids) {
        return 0;
    }

    @Override
    public Map<String, Object> integralprepay(Map<String, Object> reqMap) {
        logger.info("IntegralPayServiceImpl-------金融中心积分支付请求优店入参"+JsonUtils.objectToJson(reqMap));
        Map<String, Object> chageMap = null;
        String result = null;
        //订单号
        String orderNum = reqMap.get("orderNum").toString();
        //会员id
        String customerUuid = reqMap.get("customerUuid").toString();
        //积分支付总金额
        String payMoney = reqMap.get("payMoney").toString();
        //交易描述
        String subject = reqMap.get("subject").toString();
        //获取token
        String Authorization = reqMap.get("Authorization").toString();
        redisUtils.setKey(orderNum,Authorization,60*30);
        String  platfromMarking = reqMap.get("platfromMarking").toString();
        if(StringUtils.isEmpty(orderNum)
                ||StringUtils.isEmpty(customerUuid)||StringUtils.isEmpty(payMoney)||StringUtils.isEmpty(Authorization)){
            return ApiResult.paramIsNull();
        }

        //获取平台应用id
        int platfromId = platformPayFegin.getPlatfromId(platfromMarking);

        //拼接请求参数对接够样平台
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("customerId",customerUuid);
        requestMap.put("orderNum",orderNum);
        requestMap.put("payCurrency",payMoney);
        requestMap.put("platformBusnum",platfromMarking);
        Map<String, Object> prePayInfoMap = null;

        try {
            Map<String, String> omap = new HashMap<>();
            omap.put("Authorization",Authorization);
            //余额平台回调地址
            logger.info("integral--------拼接请求参数对接够样平台请求地址:{},对接参数:{},携带token:{}",UrlConstants.INTEGRAL_EPAY_URL,JsonUtils.objectToJson(requestMap),omap);
            result = httpClientUtils.doPostToJson(UrlConstants.INTEGRAL_EPAY_URL,requestMap,omap);
            chageMap = JsonUtils.jsonToMap(result);
            if(!"0".equals(chageMap.get("return_code"))){
                ApiResult.failure("预支付单获取失败");
            }
            logger.info("++++customerUuid:{},积分预支付信息结果:{}", requestMap.get("customerId"),JsonUtils.jsonToMap(result));
            //保存够样积分预支付同步回执
            Object temp = "";
            temp =  chageMap.get("return_code");
            String return_code = temp!= null ? temp.toString():null;
            temp =  chageMap.get("prePayInfoDO");
            String currencyPrePayInfoDO = temp!= null ? temp.toString():null;
            prePayInfoMap = JsonUtils.jsonToMap(currencyPrePayInfoDO);

            temp = prePayInfoMap.get("customerId");
            String customerId = temp!= null ? temp.toString():null;
            temp = prePayInfoMap.get("opeTime");
            String opeTime = temp!= null ? temp.toString():null;
            temp = prePayInfoMap.get("payCurrency");
            String payCurrency = temp!= null ? temp.toString():null;
            temp = prePayInfoMap.get("prepayNo");
            String prepayNo = temp!= null ? temp.toString():null;
            temp = prePayInfoMap.get("businessType");
            String businessType = temp!= null ? temp.toString():null;

            //保存回执信息
            FinancialIntegralPayReceiptDO gyintegralPayReceiptDO = new FinancialIntegralPayReceiptDO();
            gyintegralPayReceiptDO.setCustomeruuid(customerId);
            gyintegralPayReceiptDO.setGmtCreate(new Date());
            gyintegralPayReceiptDO.setGmtModified(new Date());
            gyintegralPayReceiptDO.setIsDelete(FinancialPayreceiptPlatbalanceEnumConstants.ENUM_ISDELETE_UNDEL);
            gyintegralPayReceiptDO.setPlatfromappid(String.valueOf(platfromId));
            gyintegralPayReceiptDO.setPaymoney(new BigDecimal(payCurrency));
            gyintegralPayReceiptDO.setPayno(prepayNo);
            gyintegralPayReceiptDO.setSubject(businessType);
            gyintegralPayReceiptDO.setOrderno(orderNum);
            gyintegralPayReceiptDO.setOpetime(opeTime);
            gyintegralPayReceiptDO.setResponseType("1");
            if(!return_code.equals("0")){
                gyintegralPayReceiptDO.setState("交易失败");
            }else {
                gyintegralPayReceiptDO.setState("交易成功");
            }

            logger.info("积分预支付信息保存记录"+JsonUtils.objectToJson(gyintegralPayReceiptDO));
            gyintegralPayReceiptDao.save(gyintegralPayReceiptDO);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("++++customerUuid:{},积分预支付信息失败:{},", customerUuid, e.getMessage());
            return  ApiResult.failure("积分预支付单处理失败");
        }
        return ApiResult.success(JsonUtils.objectToJson(prePayInfoMap));
    }
}
